<template>
	<!-- 物业项目-预算对标 table -->
	<div v-if="propertyTypeList.length > 0" class="card-box">
		<div v-for="(item, index) in propertyTypeList" :key="index" class="benchmarkingData-item zs-space-bottom" :class="{ isSelect: item.id == selectId }" @click="scroolPosition(item)">
			<div class="item-header">
				<span>{{ item.subject_name }}</span>
				<span class="line">|</span>
				<span>利润率</span>
			</div>
			<div class="item-main">
				<div class="main-text">
					<span class="title">{{ standard == '1' ? '标准' : '预算' }}</span>
					<div>
						<span class="val"> {{ standard == '1' ? toThousands(item.standard_unilateral) : toThousands(item.acc_month_budget) }} </span>
						<span v-if="standard == '1' && item.standard_unilateral != '-'" style="font-size: 10px">%</span>
						<span v-if="standard == '2' && item.acc_month_budget != '-'" style="font-size: 10px">%</span>
					</div>
				</div>
				<div class="main-vs">VS</div>
				<div class="main-text">
					<span class="title">实际</span>
					<div>
						<span v-if="standard == '1'" class="val" :class="item.actualColor">{{ toThousands(item.actual_unilateral) }}</span>
						<span v-else class="val" :class="item.monthColor">{{ toThousands(item.acc_month_actual) }}</span>
						<span v-if="standard == '1' && item.actual_unilateral != '-'" style="font-size: 10px">%</span>
						<span v-if="standard == '2' && item.acc_month_actual != '-'" style="font-size: 10px">%</span>
					</div>
				</div>
			</div>
		</div>
	</div>
	<hsTableV2 class="db-table-self-tootip" ref="tableRef" :loading="tableData.loading" isMultistageHeader :columns="tableData.cloumns" :data="tableData.data" fixed :multistageHeaderData="multistageData" :isFirstLevelBorder="true" :rowClassFun="tableData.rowClass"></hsTableV2>
</template>

<script setup lang="jsx">
	import { ref, reactive, computed, watch } from 'vue';
	import detailApi from '@/api/Property/detailPages';
	import { toThousands } from '@/utils/number-util';

	const props = defineProps({
		projectCode: {
			type: String,
			required: true,
			default: '',
		},
		yearmonth: {
			type: String,
			required: true,
			default: '',
		},
		isFresh: {
			type: [String, Number],
			required: true,
			default: '',
		},
		curType: {
			type: Number,
			required: true,
			default: 1,
		},
		standard: {
			type: String,
			required: true,
			default: '1',
		},
	});

	let multistageData = {};

	const tableRef = ref();

	const initMultistageData = () => {
		const year = props.yearmonth.split('-')[0];
		let month = props.yearmonth.split('-')[1];
		month[0] == 0 ? (month = month.substring(1, 2)) : '';
		multistageData['multCol2'] = {
			key: 'multCol2',
			title: month == 1 ? `${year}年${month}月` : `${year}年1-${month}月`,
			childrenIndex: [2, 3, 4, 5, 6, 7, 8, 9],
			// childrenIndex: [2, 3, 4, 5, 6]
		};
		multistageData['multCol7'] = {
			key: 'multCol7',
			title: `${year}年度`,
			childrenIndex: [10, 11, 12],
			// childrenIndex: [7, 8, 9]
		};
	};
	initMultistageData();
	const windowWidth = document.documentElement.scrollWidth;
	const celWidth = (windowWidth - 138 - 300) / 11;
	let tableData = reactive({
		loading: false,
		data: [],
		cloumns: [
			{
				key: 'id',
				dataKey: 'id',
				title: '科目编号',
				align: 'left',
				width: 100,
				fixed: 'left',
				cellRenderer: ({ rowData, rowIndex }) => {
					return (
						<div style="display:flex">
							{rowData.children?.length > 0 ? (
								<el-icon
									class={{
										'el-table-v2__expand-icon': true,
										'is-expanded-icon': rowData.expanded,
									}}
									size="12"
									onClick={() => expandFn(rowData, rowIndex)}
									style="margin-right:5px;cursor: pointer;">
									{rowData.expanded ? <ArrowDown /> : <ArrowRight />}
								</el-icon>
							) : (
								<span style="width:18px"></span>
							)}
							<span class="text-hide">{rowData.id}</span>
						</div>
					);
				},
			},
			{
				key: 'subject_name',
				dataKey: 'subject_name',
				title: '科目',
				width: 200,
				align: 'left',
				fixed: 'left',
				indentKey: 'level', // 设置缩进字段
				cellRenderer: ({ rowData }) => (
					<div style={{ display: 'flex' }}>
						<div style={{ width: `${12 * (rowData.level - 1)}px` }}></div>
						<div>{rowData.subject_name}</div>
					</div>
				),
			},
			{
				key: 'acc_month_budget',
				dataKey: 'acc_month_budget',
				title: '预算',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.acc_month_budget && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.acc_month_budget)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_budget_yuan)}</div>
					</div>)
				),
			},
			{
				key: 'acc_month_actual',
				dataKey: 'acc_month_actual',
				title: '实际',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.acc_month_actual && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.acc_month_actual)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_actual_yuan)}</div>
					</div>)
				),
			},
			{
				key: 'acc_month_rate',
				dataKey: 'acc_month_rate',
				title: '完成率',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.acc_month_rate && 
					(<div class="db-slef-tooltip">
						<span class={{ 'zs-text-red': rowData.accMonthRateColour == 2, 'zs-text-green': rowData.accMonthRateColour == 1, 'db-tooltip-txt': true }}>{`${rowData.acc_month_rate == '-' ? '-' : rowData.acc_month_rate}`}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_rate)}</div>
					</div>)
				),
			},
			{
				key: 'acc_month_yoy',
				dataKey: 'acc_month_yoy',
				title: '同比',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.acc_month_yoy && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{`${rowData.acc_month_yoy == '-' ? '-' : rowData.acc_month_yoy}`}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_yoy)}</div>
					</div>)
				),
			},
			{
				key: 'acc_month_actual_gap',
				dataKey: 'acc_month_actual_gap',
				title: '缺口',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.acc_month_actual_gap && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.acc_month_actual_gap)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_actual_gap_yuan)}</div>
					</div>)
				),
			},
			{
				key: 'standard_unilateral',
				dataKey: 'standard_unilateral',
				title: '标准单方',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.standard_unilateral && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.standard_unilateral)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.standard_unilateral)}</div>
					</div>)
				),
			},
			{
				key: 'actual_unilateral',
				dataKey: 'actual_unilateral',
				title: '实际单方',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.actual_unilateral && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.actual_unilateral)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.actual_unilateral)}</div>
					</div>)
				),
			},
			{
				key: 'standard_benchmarking',
				dataKey: 'standard_benchmarking',
				title: '标准对标',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol2',
				cellRenderer: ({ rowData }) => (
					rowData.standard_benchmarking && 
					(<div class="db-slef-tooltip">
						<span class={{ 'zs-text-red': rowData.standard_benchmarking == '不合格', 'zs-text-green': rowData.standard_benchmarking == '合格', 'zs-text-orange': rowData.standard_benchmarking == '改进', 'db-tooltip-txt': true }}>{`${rowData.standard_benchmarking == '-' ? '-' : rowData.standard_benchmarking}`}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.standard_benchmarking)}</div>
					</div>)
				),
			},
			// 本年度
			{
				key: 'year_budget',
				dataKey: 'year_budget',
				title: '预算',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol7',
				cellRenderer: ({ rowData }) => (
					rowData.year_budget && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData.year_budget)}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.year_budget_yuan)}</div>
					</div>)
				),
			},
			{
				key: 'year_actual',
				dataKey: 'year_actual',
				title: '实际',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol7',
				cellRenderer: ({ rowData }) => (
					rowData.year_actual && 
					(<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{`${rowData.year_actual == '-' ? '-' : rowData.year_actual}`}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.acc_month_actual_yuan)}</div>
					</div>)
				),
			},
			{
				key: 'year_rate',
				dataKey: 'year_rate',
				title: '完成率',
				align: 'right',
				width: celWidth,
				parentKey: 'multCol7',
				cellRenderer: ({ rowData }) => (
					rowData.year_rate && 
					(<div class="db-slef-tooltip">
						<span class={{ 'zs-text-red': rowData.yearRateColour == 2, 'zs-text-green': rowData.yearRateColour == 1, 'db-tooltip-txt': true }}>{`${rowData.year_rate == '-' ? '-' : rowData.year_rate}`}</span>
						<div class="db-tooltip-content-top">{toThousands(rowData.year_rate)}</div>
					</div>)
				),
			},
		],
		rowClass: ({ rowData }) => {
			if (rowData.subject_level == 1) {
				return 'dashboard-property-budgetcAhievement-row-header';
			}
		},
	});

	const isFresh = computed(() => {
		return props.isFresh;
	});
	watch(
		[isFresh],
		() => {
			initMultistageData();
			getCardList();
			getList();
		},
		{ deep: true },
	);

	let expandedRowKeys = ref([]);
	let curParentIndex = 0;
	const convertToFlatArray = arr => {
		arr.map(item => {
			item.lastStage = item.children ? 0 : 1; // 设置:是否为最后一级
			// item.curParentIndex = item.id.split('.')[0] - 1 // 设置统一的第一级index， 用于斑马纹
			// 设置统一的第一级index， 用于斑马纹
			if (item.subject_level == 1) {
				curParentIndex++;
				item.curParentIndex = curParentIndex;
			} else {
				item.curParentIndex = curParentIndex;
			}

			item.level = item.id.split('.').length; // 用于【科目】列缩进
			if (item.subject_level == 1) {
				expandedRowKeys.value.push(item.id); // 第一级 默认展开
			}
			if (Array.isArray(item.children)) {
				convertToFlatArray(item.children);
			}
			return item;
		});
	};

	//列表数据源
	const getList = () => {
		tableData.loading = true;
		detailApi.queryBudgetListApi({ projectCode: props.projectCode, yearmonth: props.yearmonth, showType: props.curType }).then(res => {
			if (res.data.code == 200) {
				convertToFlatArray(res.data.data);
				tableData.data = treeToFlat(res.data.data);
				tableData.loading = false;
			}
		});
	};

	// 自定义表格展开收起方法
	function expandFn(val, index) {
		let childrenList = [];
		let findSon = (data) => {
			data.forEach((item) => {
				childrenList.push(item);
				if (item.children?.length > 0 && item.expanded) {
					findSon(item.children);
				}
			});
		};
		let copyData = [...tableData.data]
		copyData.forEach((el) => {
			if (el.id == val.id) {
				findSon(el.children);
				if (val.expanded) {
					val.expanded = false;
					el.expanded = false;
					tableData.data.splice(index + 1, childrenList.length);
				} else {
					val.expanded = true;
					el.expanded = true;
					tableData.data.splice(index + 1, 0, ...childrenList);
				}
			}
		});
	}
	// 数据扁平化
	function treeToFlat(tree) {
		let result = [];
		function flatFn(data) {
			data.forEach(item => {
				if (item.subject_level == 1) {
					curParentIndex++;
					item.curParentIndex = curParentIndex;
				} else {
					item.curParentIndex = curParentIndex;
				}
				item.level = item.id.split('.').length; // 用于【科目】列缩进
				item.expanded = false;
				if (item.subject_level == 1) {
					item.expanded = true;
				}
				if (item.subject_level <= 2) result.push(item);
				if (item.children?.length > 0) {
					flatFn(item.children);
				}
			});
		}
		flatFn(tree);
		return result;
	}

	//卡片数据源
	let propertyTypeList = ref([]);
	const getCardList = async () => {
		let res = await detailApi.queryBudgetCardListApi({ projectCode: props.projectCode, yearmonth: props.yearmonth, showType: props.curType });
		if (res.data.data && res.data.data.length > 0) {
			res.data.data.forEach(item => {
				if (item.acc_month_actual != '-' && item.acc_month_budget != '-') {
					item.monthColor = Number(item.acc_month_actual) >= Number(item.acc_month_budget) ? 'zs-text-green' : 'zs-text-red';
				}
				if (item.actual_unilateral != '-' && item.standard_unilateral != '-') {
					item.actualColor = Number(item.actual_unilateral) >= Number(item.standard_unilateral) ? 'zs-text-green' : 'zs-text-red';
				}
			});
			propertyTypeList.value = res.data.data;
			selectId.value = propertyTypeList.value[0].id;
			tableRef.value.tableV2Ref.scrollTo({ scrollTop: 0 });
		}
	};

	// 点击卡片锁定table滚动条到指定位置
	let selectId = ref('');
	const scroolPosition = data => {
		selectId.value = data.id;
		let targetIndex = null;
		let scrollTop = 0;
		const index = tableData.data.findIndex(item => {
			return item.id == data.id;
		});
		targetIndex = index;
		scrollTop = scrollTop + index * 36;
		if (targetIndex != null) {
			tableRef.value.tableV2Ref.scrollTo({ scrollTop: 0 });
			expandedRowKeys.value.push('change');
			tableRef.value.tableV2Ref.scrollTo({ scrollTop: scrollTop });
		}
		expandedRowKeys.value.pop();
	};

	getCardList();
	getList();
</script>

<style scoped lang="scss">
	:deep(.zs-el-table-v2 .is-expanded-icon) {
		color: #477afd !important;
	}

	.card-box {
		display: flex;
		flex-wrap: wrap;

		.isSelect {
			background-color: #477afd;
			color: #ffffff;
		}

		.benchmarkingData-item {
			cursor: pointer;
			width: 204px;
			width: calc((100% - 60px) / 7);
			min-width: 167px;
			// height: 148px;
			border: 1px solid #eaeaea;
			border-radius: 6px;
			padding: 12px;
			margin-right: 10px;
			box-sizing: border-box;
			overflow: hidden;

			&:nth-child(7n) {
				margin-right: 0;
			}

			.item-header {
				height: 24px;
				line-height: 24px;
				font-size: 16px;
				text-align: center;
				border-bottom: 1px solid #d4d8df;
				padding-bottom: 8px;
				margin-bottom: 8px;

				.line {
					display: inline-block;
					margin: 0 10px;
				}
			}

			.item-main {
				display: flex;
				justify-content: space-between;
				margin-top: 14px;

				// margin-bottom: 7px;
				.main-text {
					display: flex;
					flex-direction: column;
					width: calc((100% - 26px) / 2);
					text-align: center;

					.title {
						display: inline-block;
						height: 18px;
						line-height: 18px;
						font-size: 12px;
					}

					.val {
						// height:34px;
						line-height: 30px;
						font-size: 20px;
						font-weight: bold;
						font-family: DIN Alternate, DIN Alternate-Bold;
					}
				}

				.main-vs {
					padding-top: 18px;
					display: flex;
					justify-content: center;
					align-items: center;
					margin: 0 6px;
					font-size: 12px;
					font-weight: bold;
					font-family: DIN Alternate, DIN Alternate-Bold;
				}
			}

			.item-footer {
				display: flex;
				justify-content: center;
				border-radius: 6px;
				padding: 3px 12px;
				font-size: 12px;
				height: 18px;
				line-height: 18px;
				opacity: 0.8;

				.footer-text-box {
					width: 90%;
					display: flex;
					justify-content: space-between;
				}
			}

			&:first-child {
				position: relative;
				overflow: initial;
				// &::after {
				// 	content: '';
				// 	height: 120px;
				// 	width: 1px;
				// 	border-left: 1px solid #eaeaea;
				// 	position: absolute;
				// 	top: 0;
				// 	right: -9px;
				// }
			}
		}
	}
</style>

<style>
	.dashboard-property-budgetcAhievement-row-header {
		height: 30px;
		font-weight: 600;
		background: #eef4fe !important;
	}
</style>
